package com.aos.iot.protocol.hll.parser.data;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import com.aos.iot.protocol.hll.util.CodeUtil;
import com.aos.iot.protocol.hll.constant.HllCmd;
import com.aos.iot.protocol.hll.constant.HllProp;
import org.springframework.stereotype.Component;

import java.util.List;

@Component("NetWorkDataParser")
public class NetWorkDataParser extends HllDataParser {

    private final List<String> encodeItems = CollUtil.newArrayList(
            HllProp.PILE_NO.getValue(),
            HllProp.SYSTEM_TCP_URL_LENGTH.getValue(),
            HllProp.SYSTEM_TCP_URL.getValue(),
            HllProp.SYSTEM_TCP_HOST.getValue(),
            HllProp.SYSTEM_TCP_PORT.getValue()
    );

    private final List<String> decodeItems = CollUtil.newArrayList(
            HllProp.PILE_NO.getValue(),
            HllProp.SYSTEM_TCP_URL_LENGTH.getValue(),
            HllProp.SYSTEM_TCP_URL.getValue(),
            HllProp.SYSTEM_TCP_HOST.getValue(),
            HllProp.SYSTEM_TCP_PORT.getValue()
    );

    @Override
    public Dict encode(String payload) {
        int urlLength = HexUtil.hexToInt(sub(payload, 10, 12, false, "00"));
        String url = HexUtil.decodeHexStr(sub(payload, 12, 12 + urlLength * 2, false, "0.0.0.0,00000"));
        List<String> split = StrUtil.split(url, ",");
        String host = split.size() == 2 ? split.get(0) : "0.0.0.0";
        String port = split.size() == 2 ? split.get(1) : "00000";
        return Dict.create()
            .set(HllProp.PILE_NO.getValue(), sub(payload, 0, 10, true, "0000000000"))
            .set(HllProp.SYSTEM_TCP_URL_LENGTH.getValue(), urlLength)
            .set(HllProp.SYSTEM_TCP_URL.getValue(), url)
            .set(HllProp.SYSTEM_TCP_HOST.getValue(), host)
            .set(HllProp.SYSTEM_TCP_PORT.getValue(), port)
            ;
    }

    @Override
    public List<String> encodeItems() {
        return encodeItems;
    }

    @Override
    public String decode(Dict data) {
        String url = StrUtil.join(",", data.get(HllProp.SYSTEM_TCP_HOST.getValue()), data.get(HllProp.SYSTEM_TCP_PORT.getValue()));
        int urlLength = StrUtil.length(url);
        data.set(HllProp.SYSTEM_TCP_URL_LENGTH.getValue(), String.format("%02x", urlLength));
        return StrUtil.join("",
            CodeUtil.highRotation(data.getStr(HllProp.PILE_NO.getValue())),
            data.getStr(HllProp.SYSTEM_TCP_URL_LENGTH.getValue()),
            HexUtil.encodeHexStr(url)
        );
    }

    @Override
    public List<String> decodeItems() {
        return decodeItems;
    }

    @Override
    public String cmd() {
        return HllCmd.NET_WORK_HOST_CHANGE;
    }

}
